﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Web.Mvc;
using Pulsus;
using SlamCms.Common;
using SlamCms.SharePointServices;
using SlamCms.Web;

namespace SlamCms.Areas._default.Controllers
{
	public class SharepointImageController : Controller
	{
		private readonly SharePointImageService _sharepointImageService;
		private readonly SlamCmsContext _slamCmsContext;

		public SharepointImageController(SharePointImageService sharepointImageService, SlamCmsContext slamCmsContext)
		{
			_sharepointImageService = sharepointImageService;
			_slamCmsContext = slamCmsContext;
		}

		[HttpGet]
		public ActionResult Index(string url, int width = 0, int height = 0, bool crop = false, int quality = 95, bool alwaysProcess = false, bool showNoAvailableImage = false)
		{
			// TODO output cache but smarter
			try
			{
				var fileData = _sharepointImageService.Retrieve(url, width, height, crop, quality, alwaysProcess);
				return this.FileData(fileData);
			}
			catch (FileNotFoundException ex)
			{
				_slamCmsContext.LogManager.CreateEvent()
										 .Level(LoggingEventLevel.Warning)
										 .Text("SharePoint image not found")
										 .AddHttpContext(this.HttpContext)
										 .AddException(ex)
										 .Push();

				if (showNoAvailableImage)
				{
					var noAvailableImageStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SlamCms.Areas._default.Content.img.not-available.gif");

					if (width > 0 && height > 0)
						noAvailableImageStream = Image.FromStream(noAvailableImageStream).Resize(width, height).ToStream(ImageFormat.Gif);

					return File(noAvailableImageStream, "image/gif");
				}

				return this.NotFound();
			}
		}
	}
}
